package anonymouschat.utils;

import java.net.InetAddress;

import anonymouschat.service.ServerEntry;

public class ServerUtils {

	public static void main(String[] args) throws Exception {

		if (args.length > 0) { // a list of servers was provided
			ListOfServers los = new ListOfServers();
			for (int i = 0; i < args.length; i++) {
				ServerUtils.rebindServerIdentity(los.getByName(args[i]));
			}
		} else { // change all local public server identity files
			System.out
					.println("This will rebind all public server IDs on this "
							+ "system to this IP address.  "
							+ "Cancel in the next 10 seconds if you don't want to do this");
			for (int i = 10; i > 0; i--) {
				try {
					System.out.print(i);
					for (int j = 0; j < 4; j++) {

						Thread.sleep(250);
						System.out.print(" .");
					}
				} catch (Exception e) {
				}
			}
			rebindAllServerIdentities();
		}
	}

	public static void rebindAllServerIdentities() throws Exception {
		ListOfServers los = new ListOfServers();
		for (ServerEntry svr : los.servers) {
			rebindServerIdentity(svr);
		}
	}

	/**
	 * Rebind a specific serve Identity
	 * 
	 * @param svrName
	 * @throws Exception
	 */
	public static void rebindServerIdentity(ServerEntry oldPublicID)
			throws Exception {
		// oldPublicID.savePublicIdentity( oldPublicID.serverName,
		// oldPublicID.serverPort, oldPublicID.publicKey );
		if (oldPublicID != null) {
			ServerEntry newPublicID = new ServerEntry(oldPublicID.serverName,
					InetAddress.getLocalHost().getHostAddress(),
					oldPublicID.serverPort, oldPublicID.publicKey);

			// store the public ID
			LocalFileOps.write(newPublicID, LocalFileOps
					.getPublicIdentityFileName(oldPublicID.serverName));
		} else {
			Print.error("Cannot modify null object.");
		}
	}

	public static void rebindSpecificServer(String serverName) throws Exception {
		ListOfServers los = new ListOfServers();
		rebindServerIdentity(los.getByName(serverName));
	}

}
